<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="科室名称" prop="departmentName">
        <el-input
          v-model="queryParams.departmentName"
          placeholder="请输入科室名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科室简介" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入科室简介"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>


      <el-form-item label="科室状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择科室状态" clearable>
          <el-option
            v-for="dict in sys_status_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:departments:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
<!----表格------------------------------------------------------->
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="departmentsList"
      row-key="departmentId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="科室编号" prop="departmentId" />
      <el-table-column label="科室名称" align="center" prop="departmentName" />
      <el-table-column label="科室简介" align="center" prop="description" />
      <el-table-column label="创建时间" align="center" prop="creationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creatorName" />
      <el-table-column label="科室状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_status_type" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:departments:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:departments:add']">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:departments:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改科室对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="departmentsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="科室编号" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="departmentsOptions"
            :props="{ value: 'departmentId', label: 'departmentName', children: 'children' }"
            value-key="departmentId"
            placeholder="请选择科室编号"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="科室名称" prop="departmentName">
          <el-input v-model="form.departmentName" placeholder="请输入科室名称" />
        </el-form-item>
        <el-form-item label="科室简介" prop="description">
          <el-input v-model="form.description" placeholder="请输入科室简介" />
        </el-form-item>

        <el-form-item label="科室状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_status_type"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Departments">
import { listDepartments, getDepartments, delDepartments, addDepartments, updateDepartments } from "@/api/system/departments";
import {formatDateTime} from "@/api/system/clinics.js";

const { proxy } = getCurrentInstance();
const { sys_status_type } = proxy.useDict('sys_status_type');

const departmentsList = ref([]);
const departmentsOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    departmentName: null,
    description: null,
    creationTime: null,
    creator: null,
    status: null
  },
  rules: {
    departmentName: [
      { required: true, message: "科室名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询科室列表 */
function getList() {
  loading.value = true;
  listDepartments(queryParams.value).then(response => {
    console.log(departmentsList.value)
    departmentsList.value = proxy.handleTree(response.data, "departmentId", "parentId");
    console.log(departmentsList.value)
    loading.value = false;
  });
}

/** 查询科室下拉树结构 */
function getTreeselect() {
  listDepartments().then(response => {
    departmentsOptions.value = [];
    const data = { departmentId: 0, departmentName: '顶级节点', children: [] };
    data.children = proxy.handleTree(response.data, "departmentId", "parentId");
    departmentsOptions.value.push(data);
  });
}
	
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    departmentId: null,
    parentId: null,
    departmentName: null,
    description: null,
    creationTime: null,
    creator: null,
    status: null
  };
  proxy.resetForm("departmentsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.departmentId) {
    form.value.parentId = row.departmentId;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加科室";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  getDepartments(row.departmentId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改科室";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["departmentsRef"].validate(valid => {
    if (valid) {
      if (form.value.departmentId != null) {

        updateDepartments(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        form.value.creationTime=formatDateTime(new Date())
form.value.creator=localStorage.getItem("userId")
        addDepartments(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
      getList()
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除科室编号为"' + row.departmentId + '"的数据项？').then(function() {
    return delDepartments(row.departmentId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

getList();
</script>
